﻿// 预热活动首页
$(function () {
    var userId = getUrlParam('userId');
    var userType = getUrlParam('userType');
    var activity = 'LIGHT_COUPONS_201706;LIGHT_TWO_COUPONS_201706';
    var token = getUrlParam('token');


    if (userId == '') {
        userId = sessionStorage.getItem('userId');
        userType = sessionStorage.getItem('userType');
    }
    sessionStorage.setItem('userId', userId);
    sessionStorage.setItem('userType', userType);
    sessionStorage.setItem('token', token);


    // getUser(userId, userType);// 买点
    //alert('拿数据=' + userId + ',' + token);

    // 判断登陆+
    if (TypeOfBrowser() == 'app') {
        var userInfo = getUserIdAndToken();
        //  alert('判断登陆=' + TypeOfBrowser());
        setTimeout(function () {
            userInfo = getUserIdAndToken();
            // getLightTime('coupon/getLightTimes', userInfo.userId, 'app', activity, userInfo.token, function (num) { setLightNum(num) });
            setTimeout(function() {
                userInfo = getUserIdAndToken();
                if (!userInfo.userId || !userInfo.token) {
                    _appLogin(function() {
                        userInfo = getUserIdAndToken();
                        //    alert("APP登陆后拿数据= " + JSON.stringify(userInfo) + ', userInfo.token=' + userInfo.token);

                        setTimeout(function() {
                            userInfo = getUserIdAndToken();
                            sessionStorage.setItem('userId', userInfo.userId);
                            sessionStorage.setItem('userType', 'app');
                            sessionStorage.setItem('token', userInfo.token);
                            sessionStorage.setItem('deviceId', userInfo.deviceId);
                            userId = sessionStorage.getItem('userId');
                            userType = 'app';
                            token = sessionStorage.getItem('token');

                            getLightTime('coupon/getLightTimes', userId, userType, activity, token, function(num) { setLightNum(num) });

                        }, 200)


                    }); //先登录

                    setTimeout(function() {

                        AW.toast.show({
                            message: '请登录',
                            type: 'none',
                            callContainer: true
                        });
                    }, 200);
                    return false;
                } else {
                    sessionStorage.setItem('userId', userInfo.userId);
                    sessionStorage.setItem('userType', 'app');
                    sessionStorage.setItem('token', userInfo.token);
                    sessionStorage.setItem('deviceId', userInfo.deviceId);
                    userId = sessionStorage.getItem('userId');
                    userType = 'app';
                    token = sessionStorage.getItem('token');


                    getLightTime('coupon/getLightTimes', userId, userType, activity, token, function(num) { setLightNum(num) });
                }
            }, 200);

            setTimeout(function() {
                //买点 
                window.cxytj.recordUserBehavior({
                    eventId: 'index_load-APP', //事件标记
                    eventType: '2', //事件类型
                    attr1: '进入周年庆首页', //属性1
                    eventTime: window.cxytj.getNowFormatDate(),  //触发时间
                    eventPropertis: {}, //事件属性，以json形式，对事件相关扩展属性进行记录上传
                    curPageInfo: '', //当前页信息
                    prevPageInfo: '', //上一页信息
                    startTime: window.cxytj.getNowFormatDate(), //开始时间
                    channel: TypeOfBrowser(), //推广渠道
                    userId: sessionStorage.getItem('userId'), //用户ID
                    productUserId: sessionStorage.getItem('deviceId') // APP
                });
            }, 300);
        }, 450);

        

    } else if (TypeOfBrowser() == 'unKnown') {
        // 非APP渠道
        popFUN('noBTN', '', '<p class="f14 colorGray padTB5">该浏览器无法打开页面</p>', '');
        // var lightTimes;
        /* AW.toast.show({
             message: '该浏览器无法打开页面',
             type: 'none',
             callContainer: true
         });*/
    }
    else {
        // 非APP渠道
        // 如果没有单点登录，跳去登陆
        if (!getUrlParam('token')) {
            //   alert('准备跳转到登陆=' + getUrlParam('token'))
            window.location.href = fromUrl('signOn');
            return false;
        }
        //   alert('第1次请求getLightTime' + $('#data').html());
        // var lightTimes;
        getLightTime('coupon/getLightTimes', userId, userType, activity, token, function (num) { setLightNum(num) });

        // 如果5秒后没有数据，再请求一次
        setTimeout(function () {

            if ($('#data').html() == '?') {
                //      alert('第2次请求getLightTime' + $('#data').html());
                getLightTime('coupon/getLightTimes', userId, userType, activity, token, function (num) { setLightNum(num) });
            }
        }, 5000);


        //买点 
        window.cxytj.recordUserBehavior({
            eventId: 'index_loading-WX-qq-ali', //事件标记
            eventType: '2', //事件类型
            attr1: '进入周年庆首页', //属性1
            eventTime: window.cxytj.getNowFormatDate(),  //触发时间
            eventPropertis: {}, //事件属性，以json形式，对事件相关扩展属性进行记录上传
            curPageInfo: '', //当前页信息
            prevPageInfo: '', //上一页信息
            startTime: window.cxytj.getNowFormatDate(), //开始时间
            channel: TypeOfBrowser(), //推广渠道
            userId: sessionStorage.getItem('userId'), //用户ID
            productUserId: sessionStorage.getItem('deviceId') // APP
        });

    }


    /* 老用户，点亮第一次，未支付按钮 ：点击事件 */
    $(".gotopay").click(function () {

        var numlightTimes = sessionStorage.getItem('LightNumStorage-lightTimes');
        var numisNewer = sessionStorage.getItem('LightNumStorage-isNewer');
        var numisPay = sessionStorage.getItem('LightNumStorage-isPay');
        if (numlightTimes == 2) {
            numlightTimes = 1
        }
        switch (TypeOfBrowser()) {
            case 'alipay':
                AlipayJSBridge.call('openInBrowser', {
                    url: './show.html?lightTimes=' + numlightTimes + '&isNewer=' + numisNewer + '&isPay=' + numisPay
                });
                break;
            default:
                window.location = './show.html?lightTimes=' + numlightTimes + '&isNewer=' + numisNewer + '&isPay=' + numisPay
        }
    })


    /* 领取礼包按钮 */
    $('#lightBTN').click(function () {
        var tips = '请稍等';
        // 按钮是especially=loading，不能点击
        if ($("#lightBTN").attr("class").indexOf("especially") > 0) {
            if (TypeOfBrowser() == 'app') {
                var userInfo = getUserIdAndToken();
                //  alert('判断登陆=' + TypeOfBrowser());
                setTimeout(function () {
                    userInfo = getUserIdAndToken();
                    if (!userInfo.userId || !userInfo.token) {
                        userInfo = getUserIdAndToken();
                        _appLogin(function () {

                            setTimeout(function () {
                                userInfo = getUserIdAndToken();
                                userInfo = getUserIdAndToken();
                                sessionStorage.setItem('userId', userInfo.userId);
                                sessionStorage.setItem('userType', 'app');
                                sessionStorage.setItem('token', userInfo.token);
                                userId = sessionStorage.getItem('userId');
                                userType = 'app';
                                token = sessionStorage.getItem('token');

                                getLightTime('coupon/getLightTimes', userId, userType, activity, token, function (num) { setLightNum(num) });
                            }, 500)

                        }); //先登录

                        setTimeout(function () {

                            AW.toast.show({
                                message: '请登录',
                                type: 'none',
                                callContainer: true
                            });
                        }, 200);
                        return false;
                    } else {

                        userInfo = getUserIdAndToken();
                        sessionStorage.setItem('userId', userInfo.userId);
                        sessionStorage.setItem('userType', 'app');
                        sessionStorage.setItem('token', userInfo.token);
                        userId = sessionStorage.getItem('userId');
                        userType = 'app';
                        token = sessionStorage.getItem('token');

                        getLightTime('coupon/getLightTimes', userId, userType, activity, token, function (num) { setLightNum(num) });
                    }
                }, 100);

            } else if (TypeOfBrowser() == 'unKnown') {
                // 非APP渠道
                //    tips = '该浏览器无法打开页面';
                popFUN('noBTN', '', '<p class="f14 colorGray padTB5">该浏览器无法打开页面</p>', '');

            }
            else {
                // 非APP渠道
                // 如果没有单点登录，跳去登陆
                if (!getUrlParam('token')) {
                    //   alert('准备跳转到登陆=' + getUrlParam('token'))
                    window.location.href = fromUrl('signOn');
                    return false;
                }

                getLightTime('coupon/getLightTimes', userId, userType, activity, token, function (num) { setLightNum(num) });

                // 如果5秒后没有数据，再请求一次
                setTimeout(function () {

                    if ($('#data').html() == '?') {
                        //      alert('第2次请求getLightTime' + $('#data').html());
                        getLightTime('coupon/getLightTimes', userId, userType, activity, token, function (num) { setLightNum(num) });
                    }
                }, 5000);



            }
            /*  AW.toast.show({
                  message: tips,
                  type: 'none',
                  callContainer: true
              });*/
            return false;
        }
        // 已经不是当前活动时间，不能点击
        if (sessionStorage.getItem('LightNumStorage-activityType') == 2) {

            AW.toast.show({
                message: '点亮活动已经结束，期待更多精彩',
                type: 'none',
                callContainer: true
            });
            return false;
        }
        // 当前活动时间，但已经点击2次了，不能点击
        if ($("#lightBTN").attr("class").indexOf("btn3") > 0) {
            return false;
        }
        //  console.log('lightBTN被点击了');
        // 添加买点
        window.cxytj.recordUserBehavior({
            eventId: 'index_lightBTN', //事件标记
            eventType: '2', //事件类型
            attr1: '点击点亮蜡烛', //属性1
            eventTime: window.cxytj.getNowFormatDate(),  //触发时间
            eventPropertis: {}, //事件属性，以json形式，对事件相关扩展属性进行记录上传
            curPageInfo: '', //当前页信息
            prevPageInfo: '', //上一页信息
            startTime: window.cxytj.getNowFormatDate(), //开始时间
            channel: TypeOfBrowser(), //推广渠道
            userId: sessionStorage.getItem('userId'), //用户ID
            productUserId: sessionStorage.getItem('deviceId') // APP
        });
        // 领取礼物
        // 判断渠道


        getLightTime('coupon/getGift', userId, userType, activity, token, function (num) { setLightBtn(num) });


    });


    /* 第一次点击优惠，有提示 
     * 
     */
    $('.index-body').click(function () {
        //alert("sessionStorage.getIte= " + sessionStorage.getItem("LightNumStorage-lightTimes"));
        var lightTimes = 0;
        if (token == null) {
            AW.toast.show({
                message: '快快点亮蜡烛吧~',
                type: 'none',
                callContainer: true
            });
            return false;
        }
        if (sessionStorage.getItem("LightNumStorage-lightTimes") > 0) {
            lightTimes = sessionStorage.getItem("LightNumStorage-lightTimes");
        } else {
            getLightTime('coupon/getLightTimes', userId, userType, activity, token, function (num) {
                sessionStorage.setItem("LightNumStorage-lightTimes", num.lightTimes);
                sessionStorage.setItem("LightNumStorage-isNewer", num.isNewer);
                sessionStorage.setItem("LightNumStorage-isPay", num.isPay);
                sessionStorage.setItem("LightNumStorage-activityType", num.activityType);
                //        (JSON.stringify(num));

                if (num.lightTimes == 0) {
                    AW.toast.show({
                        message: '快快点亮蜡烛吧~',
                        type: 'none',
                        callContainer: true
                    });
                }
            });
        }


    });


    /* 蜡烛事件:点亮对应的蜡烛数量，下面优惠券提示修改 */
    function setLightNum(num) {
        sessionStorage.setItem("LightNumStorage-lightTimes", num.lightTimes);
        sessionStorage.setItem("LightNumStorage-isNewer", num.isNewer);
        sessionStorage.setItem("LightNumStorage-isPay", num.isPay);
        sessionStorage.setItem("LightNumStorage-activityType", num.activityType);
        console.log('支付返回数据', num.isPay);

        // 输出距离开始的日期
        timeDifference(num.date, '2017/06/15 0:0:0');


        // 蜡烛数量 :参加人数
        $('#allCandle1Nums').html(num.actor);

        // 已经领取的优惠券
        var times = num.lightTimes;//num.lightTimes ;
        var candle1Num = '';
        //点亮蜡烛
        sessionStorage.setItem("lightTimesStorage", times); // 0,第一天；1，第2 次；2表示不能领取了


        // 替换优惠券上面的文字
        if (num.lightTimes >= 1 && num.isPay == 1) {
            $('.index-tlt').eq(0).html('已领取，待发放');
        }
        if (num.lightTimes == 2) {
            $('.index-tlt').eq(1).html('已领取，待发放');
        }


        if (num.lightTimes) {
            if (num.isGet) {
                if (num.isPay == 0 && num.isNewer == 0) {
                    $('.gotopay').show();
                }
            } else {
                $('.index-tlt').eq(0).html('未抢到');
            }

        }

        // 新用户和老用户的优惠券不同
        var isNewer = num.isNewer;
        //$('.index-body').eq(0).html('<img class="img" src="images/index/cp' + isNewer + '.png" alt="车行易违章查询代办" />');


        switch (times) {
            case 0:
                $("#lightBTN").attr("class", "brn-PB btn1");
                break;
            case 1:
                if (sessionStorage.getItem("resultStorage") == 1) {
                    $("#lightBTN").attr("class", "brn-PB btn2");
                } else {
                    $("#lightBTN").attr("class", "brn-PB btn1");
                }
                break;
            case 2:
                $("#lightBTN").attr("class", "brn-PB btn3").next().hide();
                break;
            default:
        }
        for (var i = 0; i < times * 3 ; i++) {
            candle1Num = candle1Num + '<div class="candle1-' + i + '"></div>';
            $('#candle1').html(candle1Num);
        }
        var name, value;
        var str = location.href; //取得整个地址栏
        var num = str.indexOf("?")
        str = str.substr(num + 1);

        window.location = './activity.html?' + str;

    }



    /* 点击点亮按钮事件： */
    function setLightBtn(num) {
        //  alert('接口返回数据：result=' + JSON.stringify(num));
        var userInfo = getUserIdAndToken();
        var tips = '';
        sessionStorage.setItem("resultStorage", num.result); // 0,领取失败；1，表示领取成功；2表示重复领取
        if (num.overTimes == 1) {
            popFUN('noBTN', '', '<p class="f14 colorOrange padTB5">遗憾！没有抢到专属红包,</p><p class="f14 colorOrange padTB5">手气就只差了一点点!</p>', '');
            $('.index-tlt').eq(0).html('未抢到');
            var candle1Num = '';
            for (var i = 0; i < 3 ; i++) { // 点亮蜡烛
                candle1Num = candle1Num + '<div class="candle1-' + i + '"></div>';
                $('#candle1').html(candle1Num);
            }
            return false;
        }
        switch (num.result) {
            case 1:
                tips = '你的礼包正在派发...';
                // 领取礼物
                // 判断渠道
                if (TypeOfBrowser() == 'app') {
                    userId = userInfo.userId;
                    userType = 'app';
                    token = userInfo.token;
                }

                getLightTime('coupon/getLightTimes', userId, userType, activity, token, function (newNum) {

                    //alert('接口返回数据-2：result=' + num.result + ', newNum=' + JSON.stringify(newNum));
                    setLightNum(newNum); // 改变页面效果 
                    setTimeout(function () {


                        switch (TypeOfBrowser()) {
                            case 'alipay':
                                AlipayJSBridge.call('openInBrowser', {
                                    url: './show.html?lightTimes=' + newNum.lightTimes + '&isNewer=' + newNum.isNewer + '&isPay=' + newNum.isPay
                                });
                                break;
                            default:
                                window.location = './show.html?lightTimes=' + newNum.lightTimes + '&isNewer=' + newNum.isNewer + '&isPay=' + newNum.isPay
                        }

                    }, 1000)

                });

                break;
            case 2:
                getLightTime('coupon/getLightTimes', userId, userType, activity, token, function (newNum) {
                    var aaaa = newNum.lightTimes == 1 && num.result == 2;
                    //  alert('接口返回数据-1：result=' + num.result + ', newNum=' + JSON.stringify(newNum) + ',' + aaaa);
                    if (newNum.lightTimes == 1 && num.result == 2) {
                        AW.toast.show({
                            message: '您今天的火柴已用完，明天再来吧！',
                            type: 'none',
                            callContainer: true
                        });
                    }
                });

                break;
            default:
                tips = '提交失败，请重新点亮';
        }

        if (tips != '') {
            AW.toast.show({
                message: tips,
                type: 'none',
                callContainer: true
            });
        }


    }
    /* 倒计时*/
    function timeDifference(begintime, endtime) {
        //begintime 需要是字符串
        //  console.log(begintime, begintime.toString());

        //begintime 为开始时间  
        var begintime_ms = Date.parse(new Date(begintime.replace(/-/g, "/")));   // begintime 为开始时间
        var endtime_ms = Date.parse(new Date(endtime.replace(/-/g, "/")));   // endtime 为结束时间  

        var date3 = endtime_ms - begintime_ms;  //时间差的毫秒数  

        if (date3 < 0) {
           
        }

        //计算出相差天数  
        var days = Math.floor(date3 / (24 * 3600 * 1000));

        //计算出小时数  

        var leave1 = date3 % (24 * 3600 * 1000);   //计算天数后剩余的毫秒数  
        var hours = Math.floor(leave1 / (3600 * 1000));
        //计算相差分钟数  
        var leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数  
        var minutes = Math.floor(leave2 / (60 * 1000));

        // alert(" 相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒")
        $('#data').html(days);
        $('#hour').html(hours);
        $('#minutes').html(minutes);

        // 计时动画
        sessionStorage.setItem('datesStorage', begintime);
        circulation(begintime);

    }


    /* 倒计时，循环计时 */

    function circulation(begintime) {
        setTimeout(function () {
            var begintime_ms = Date.parse(new Date(begintime.replace(/-/g, "/")));   // begintime 为开始时间
            var nt = new Date();//定义一个新时间
            nt.setTime(begintime_ms + 1000 * 60);//设置新时间比旧时间多一分钟
            timeDifference(nt.toString(), '2017/06/15 0:0:0');
        }, 60000); // 开始倒计时
    }


});